//########################################################################
//## (C) by Edwin Vriethoff under Microsoft Reciprocal License (Ms-RL)  ##
//## See http://www.codeplex.com/SPUserPoll/license for full license    ##
//##                                                                    ##
//## http://edwin.vriethoff.net http://www.codeplex.com/SPUserPoll/     ##
//########################################################################

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using SPUserPoll.Data.Components;
using System.Data;

namespace SPUserPoll.Business.Components
{
    public class ManageLists
    {
        const string c_AdminList = "Available SPUserPolls";
        const string c_CacheResultsKey = "SPUserPollResultsTable_{0}";
        const string c_CacheAnswerKey = "SPUserPollAnswerTable_{0}";

        /// <summary>
        /// Register a new vote
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="responseID"></param>
        /// <param name="pollID"></param>
        /// <param name="anonymous"></param>
        public static void RegisterVote(string userName, int responseID, string pollID, bool anonymous)
        {
            if (anonymous == true)
                userName = User.CreateAnonymousName(userName);

            ResponseList responseList = new ResponseList();
            responseList.RegisterVote(pollID, userName, responseID, false);

        }


        /// <summary>
        /// Check if the admin lists already exists
        /// </summary>
        /// <param name="web"></param>
        /// <returns></returns>
        private static bool DoesAdminListExist(SPWeb web)
        {
            try
            {
                SPList adminList = web.Lists[c_AdminList];
                return true;
            }
            catch
            {
                //If exception is thrown the list does not exist
                return false;
            }
        }

        /// <summary>
        /// returns the poll title
        /// </summary>
        /// <param name="pollID"></param>
        /// <returns></returns>
        private static string GetPollTitle(string pollID)
        {
            return AdminList.GetPollTitle(pollID);
        }

        /// <summary>
        /// Returns the name of the answerslist
        /// </summary>
        /// <param name="pollID"></param>
        /// <returns></returns>
        public static string GetAnswerListName()
        {
            return AnswersList.GetAnswersListName();
        }

        /// <summary>
        /// Returns the path to the folder of the answer list
        /// </summary>
        /// <param name="pollID"></param>
        /// <returns></returns>
        public static string GetAnswerFolderPath(string pollID)
        {
            return AnswersList.GetAnswerFolderPath(pollID);
        }

        /// <summary>
        /// returns the path to the folder of the response list
        /// </summary>
        /// <param name="pollID"></param>
        /// <returns></returns>
        public static string GetResponseFolderPath(string pollID)
        {
            return ResponseList.GetResponseFolderPath(pollID);
        }

        
        /// <summary>
        /// Returns the name of the responselist
        /// </summary>
        /// <param name="pollID"></param>
        /// <returns></returns>
        public static string GetResponseListName()
        {
            return ResponseList.GetResponseListName();
        }

        /// <summary>
        /// Checks if the poll lists are already created
        /// </summary>
        /// <param name="pollID"></param>
        /// <returns></returns>
        public static bool DoesPollListExist(string pollID)
        {
            string pollAnswersList = GetAnswerListName();

            SPWeb web = SPContext.Current.Web.Site.OpenWeb(); //do not dispose
            try
            {
                SPList pollList = web.Lists[pollAnswersList];
                return true;
            }
            catch
            {
                //If exception is thrown the list does not exist
                return false;
            }
        }

        private static SPList InitiateAdminList()
        {
            //Open the sitecollection
            SPWeb web = SPContext.Current.Web.Site.RootWeb; //do not dispose
            SPList adminList = null;

            if (DoesAdminListExist(web))
            {
                //the list exists. reference it
                adminList = web.Lists[c_AdminList];
            }
            else
            {
                //the list does not exist create it
                Data.Components.AdminList dataAdminList = new Data.Components.AdminList();
                adminList = dataAdminList.CreateList(web);
            }

            return adminList;
        }

        /// <summary>
        /// Check if answers are already provided
        /// </summary>
        /// <param name="pollID"></param>
        /// <returns></returns>
        public static bool AreAnswersAvailableForPoll(string pollID)
        {
            AnswersList answerList = new AnswersList();
            if (answerList.ContainsAnswers(pollID) == true)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// check if the poll name is already in use
        /// </summary>
        /// <param name="pollName"></param>
        /// <returns></returns>
        public static bool PollNameExists(string pollName)
        {
            AnswersList answerList = new AnswersList();
            return answerList.AnswerFolderExist(pollName);
        }

        /// <summary>
        /// Creates default lists for the poll
        /// </summary>
        /// <param name="pollID"></param>
        /// <param name="pollTitle"></param>
        public static void CreatePollLists(string pollID, string pollTitle)
        {
            //create poll lists
            AnswersList answerList = new AnswersList();
            ResponseList responseList = new ResponseList();

            answerList.RegisterPoll(SPContext.Current.Web, pollTitle, pollID);
            responseList.RegisterPoll(SPContext.Current.Web, pollTitle, pollID);
        }

        /// <summary>
        /// Edit the poll registration in the admin list
        /// </summary>
        /// <param name="pollID"></param>
        /// <param name="pollTitle"></param>
        /// <param name="pollQuestion"></param>
        /// <param name="siteName"></param>
        /// <param name="published"></param>
        /// <param name="pageUrl"></param>
        public static void AddOrUpdatePollRegistration(string pollID, string pollTitle, string pollQuestion, string siteName, bool published, string pageUrl)
        {
            //Make sure the admin list does exist
            InitiateAdminList();
            
            AdminList adminList = new AdminList();
            adminList.AddOrUpdatePollRegistration(pollID, pollTitle, pollQuestion, siteName, published, pageUrl);
        }

        /// <summary>
        /// Updates the publication state in the admin table
        /// </summary>
        /// <param name="pollID"></param>
        /// <param name="published"></param>
        public static void UpdatePollPublicationState(string pollID, bool published)
        {
            AdminList adminList = new AdminList();
            adminList.UpdatePollPublicationSate(pollID, published);
        }

        /// <summary>
        /// Get all answers for specified poll
        /// </summary>
        /// <param name="pollID"></param>
        /// <returns></returns>
        public static DataTable GetAnswersForPoll(string pollID, bool useCache)
        {
            DataTable answersTable = null;

            //cache will only be used for normal users. if admin user we show no cache info
            if (useCache == true)
            {
                //use cache
                object fromCache = Cache.GetFromCache(string.Format(c_CacheAnswerKey, pollID));
                if (fromCache != null)
                {
                    answersTable = (DataTable)fromCache;
                }
                else
                {
                    AnswersList answersList = new AnswersList();
                    answersTable = answersList.GetPollAnswers(pollID);
                    Cache.AddToCache(string.Format(c_CacheAnswerKey, pollID), answersTable);
                }
            }
            else
            {
                AnswersList answersList = new AnswersList();
                answersTable = answersList.GetPollAnswers(pollID);
            }
            return answersTable;
        }

        /// <summary>
        /// Get result table for specified poll
        /// </summary>
        /// <param name="pollID"></param>
        /// <returns></returns>
        public static DataTable GetResultTableForPoll(string pollID)
        {
            DataTable resultTable = null;
            
            //use cache
            object fromCache = Cache.GetFromCache(string.Format(c_CacheResultsKey, pollID));
            if (fromCache != null)
                resultTable = (DataTable)fromCache;
            else
            {
                ResultTable getResultTable = new ResultTable(pollID);
                resultTable = getResultTable.ReturnResultTable();
                Cache.AddToCache(string.Format(c_CacheResultsKey, pollID), resultTable);
            }
            return resultTable;
        }

        /// <summary>
        /// Deletes all available votes for the specified poll 
        /// </summary>
        /// <param name="pollID"></param>
        public static void DeleteVotesForPoll(string pollID)
        {
            ResponseList responseList = new ResponseList();
            responseList.DeleteAllResponsesForPoll(SPContext.Current.Web, pollID);
        }

        /// <summary>
        /// Reset the cache belonging to a poll (used by eventhandler)
        /// </summary>
        /// <param name="pollName"></param>
        /// <param name="listType"></param>
        public static void ResetCache(SPWeb web, string pollName, Types.CacheList listType)
        {
            string pollID = AdminList.GetPollID(pollName, web);
            if (string.IsNullOrEmpty(pollID) == false)
            {
                //rese the cache for this poll
                if (listType == Types.CacheList.Answers)
                {
                    Cache.RemoveFromCache(string.Format(c_CacheAnswerKey, pollID));
                }
                else
                {
                    Cache.RemoveFromCache(string.Format(c_CacheResultsKey, pollID));
                }
            }

        }
    }
}
